// pages/articleContent/articleContent.js
const app = getApp()
const tools = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    status:2,
    article:[],
    article_id: 0,
    commentList: [],
    comment: [],
    // 文章内容
    comment_content: "",
    isLike: false,
    isCollect: false,
    likeNum:0,  //点赞数
    // 点赞图标路径
    imgUrl: "../../static/images/like1.png",
    collectUrl: "../../static/images/collection1.png",
    // 父评论输入框
    inputValue: "",
    // 回复输入框
    repleyInputValue: "",
    // 用户个人信息
    userInfo: {
      avatar: '',
      nickName: '',
      user_id:''
    },
    // 用户是否已经登录
    isShowUserName:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

     // 获取用户登录信息
     let user_id = wx.getStorageSync('user_id');
     let nickName = wx.getStorageSync('nickName');
     let avatar = wx.getStorageSync('avatar');
     this.setData({
       userInfo: {
         avatar: avatar,
         nickName: nickName,
         user_id:user_id
       }
     });

     this.setData({article_id: options.id});

    this.commentList(options.id)
    // this.likeList(options.id)
    console.log('------article_id',options.id)
    let articles = app.globalData.articleList;  
    console.log('-----------------文章内容',articles)   
    let articleinfo = '';
    for (let i = 0; i < articles.length;i++){
      console.log('---------i',articles[i].article_id)
      if(+options.id === articles[i].article_id){
        articleinfo = articles[i]
      }
    }  
    this.setData({
      articleinfo: articleinfo,
    });
    
	  const _ts = this;
	  //将markdown内容转换为towxml数据
	  let data = app.towxml.toJson(
		  articleinfo.content,               // `markdown`或`html`文本内容
		  'markdown'              // `markdown`或`html`
	  );

	  //前台初始化小程序数据（2.1.2新增，如果小程序中无相对资源需要添加`base`根地址，也无`audio`内容可无需初始化）
	  data = app.towxml.initData(data, {
		  base: '',    // 需要解析的内容中相对路径的资源`base`地址
		  app: _ts                     // 传入小程序页面的`this`对象，以用于音频播放器初始化
	  });

	  //设置文档显示主题，默认'light' dark
	  data.theme = 'light';

	  //设置数据
	  _ts.setData({
		  article: data
    });
    if(wx.getStorageSync('user_id')){
      this.getlikeList()
      this.getcollectList()
    }
  },

  wxLogin(e) {
    let _that = this;
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        _that.setData({
          userInfo: res.userInfo,
          hasUserInfo: true,
          isShowUserName: true
        })

        wx.login({
          success: (res) => {
            if (res.code) {
              wx.request({
                url: 'https://xiaxueruo.com/api/User/userInfo',
                data: {
                  code: res.code,
                  nickName: _that.data.userInfo.nickName,
                  avatar: _that.data.userInfo.avatarUrl
                },
                method: 'GET',
                success: function (res) {
                  // 接口返回openid或者一个能标识身份的标识，比如user_id
                  console.log("成功：", res.data);

                  let user = res.data;
                  console.log(user)
                  wx.setStorageSync('session3rd', res.data.session3rd)  // 把唯一标识缓存
                  wx.setStorageSync('user_id', res.data.user_id)
                  wx.setStorageSync('nickName', res.data.nickName)
                  wx.setStorageSync('avatar', res.data.avatarUrl)
                  // 读取缓存 
                  wx.getStorageSync('session3rd')
                  
                  _that.setData({
                    userInfo: {
                      avatarUrl: user.avatarUrl,
                      nickName: user.nickName,
                      user_id: user.user_id
                    },
                    isShowUserName: true
                  });
                  console.log('reLaunch', '/pages/articleContent/articleContent?id='+_that.data.article_id);
                  wx.reLaunch({
                    url: '/pages/articleContent/articleContent?id='+_that.data.article_id
                  })                    
                }
              })
            }
          }
        })

      }

    })
  },

  onSend() {
    if(!wx.getStorageSync('user_id')){
      this.wxLogin() //登录
    }else{
      let input = this.data.inputValue
      if (input == "" || input.trim().length == 0) {
          wx.showToast({
            title: '要输入内容噢~',
          })
      }else{
        // this.commentList = this.data.commentList,
        console.log("名称：", wx.getStorageSync('nickName'))
        console.log("内容：", this.data.inputValue)
        console.log("文章id：", this.data.commentList.article_id)
        console.log("头像：", wx.getStorageSync('avatar'))
        let _this = this;
        wx.request({
          url: 'https://xiaxueruo.com/api/comment/add?article_id='+this.data.commentList.article_id+"&comment_content="+this.data.inputValue+"&nickName="+wx.getStorageSync('nickName')+"&avatar="+wx.getStorageSync('avatar') +'&user_id='+ wx.getStorageSync('user_id'),
          success: function(res){
            console.log(res)
            // _this.data.userInfo.avatarUrl=res.data.data.comment.avatar
            // console.log(_this.data.articleinfo.article_id)
            _this.data.commentList.unshift(res.data.data.commentList)
            _this.setData({
              commentList:_this.data.commentList,
              // article_id: _this.data.articleinfo.article_id,
              inputValue: ""
            })
            wx.showToast({
              title: '评论成功',
              icon: 'success',
              duration: 1500,
            })
          }
        })
      } 
    }
  },
    

  onMark:function(){
    if(!wx.getStorageSync('user_id')){
      this.wxLogin() //登录
    }else{
      let that = this
      let article_id=that.data.articleinfo.article_id
      // let user_id = wx.getStorageSync('user_id')
      if(that.data.collectUrl=="../../static/images/collection1.png"){
        wx.request({
          url: 'https://xiaxueruo.com/api/collect/updateCollect',
          data:{
            article_id:article_id,
            user_id:wx.getStorageSync('user_id'),
            status: that.data.status,
          },
          success:function(res){
            console.log(666,res.data)
            // wx.setStorageSync('status', that.data.status)
            that.setData({
              collectUrl:"../../static/images/collection2.png",
              isCollect:true,
              status:1
            }) 
            wx.showToast({
              title: '已收藏',
              icon: 'success',
              duration: 1500,
            })
          }
        })
      }else{
        //取消收藏
        wx.request({
          url: 'https://xiaxueruo.com/api/collect/updateCollect',
          data:{
            article_id:article_id,
            user_id:wx.getStorageSync('user_id'),
            status: that.data.status,
          },
          success:function(res){
            console.log(666,res.data)
            that.setData({
              collectUrl:"../../static/images/collection1.png",
              isCollect:false,
              status:2
            }) 
            wx.showToast({
              title: '取消收藏',
              icon: 'success',
              duration: 1500,
            })
          }
        })
      }
    }
  },

  onLike:function(){
    if(!wx.getStorageSync('user_id')){
      this.wxLogin() //登录
    }else{
      let that = this
      let article_id=that.data.articleinfo.article_id
      if(that.data.imgUrl=="../../static/images/like1.png"){
        wx.request({
          url: 'https://xiaxueruo.com/api/like/updatelike',
          data:{
            article_id:article_id,
            user_id:wx.getStorageSync('user_id'),
            status: that.data.status,
            // status: sendStatus,
          },
          success:function(res){
            console.log(333, res.data)
            wx.setStorageSync('status', that.data.status)
            // 接口返回修改后的状态，记录下来
            // this.status = res.data.status;
            that.setData({
              imgUrl:"../../static/images/like2.png",
              isLike:true,
              status:1 
            }) 
            wx.showToast({
              title: '已点赞',
              icon: 'success',
              duration: 1500,
            })
          }
        })
      }else{
        //取消点赞
        wx.request({
          url: 'https://xiaxueruo.com/api/like/updatelike',
          data:{
            article_id:article_id,
            user_id:wx.getStorageSync('user_id'),
            status: that.data.status,
          },
          success:function(res){
            console.log(333,res.data)
            that.setData({
              imgUrl:"../../static/images/like1.png",
              isLike:false,
              status:2
            }) 
            wx.showToast({
              title: '取消点赞',
              icon: 'success',
              duration: 1500,
            })
          }
        })
      }
    }
  },

  // 在输入时获取搜索框的文本
  getInputBoxValue(e) {
    this.data.inputValue = e.detail.value;
  },

  // 在输入时获取搜索框的文本
  getRepleyInputBoxValue(e) {
    this.data.repleyInputValue = e.detail.value;
  },


 	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function (res) {
    return{title:'文章详情'}
},
onShareTimeline:function(res){
  return{
    title:'转发到朋友圈',
    
  }
},

  	/**
	 * 评论
	 */
  commentList(article_id){
    let that = this
    console.log('------------1',article_id);
    wx.request({
      url: 'https://xiaxueruo.com/api/comment/list?article_id='+article_id,
      header: {
        'content-type': 'application/json'
      },
      method: 'GET',//get或者post
      
      success: function (res) {
        console.log(".....",res)//接口返回值
        that.setData({
          commentList: res.data.data.commentList
        })
      }
    })
  },

  /**
   * 获取点赞列表
   */
  getlikeList(){
    let that = this
    console.log('------------that1',that);
    wx.request({
      url: 'https://www.xiaxueruo.com/api/like/searchlike?article_id='+this.options.id+'&user_id='+ wx.getStorageSync('user_id'),
      header: { 'content-type': 'application/json' },
      method: 'GET',//get或者post
      success: function (res) {
        console.log("..........status",res.data.data)//接口返回值
        if (res.data.data.result.status = 1) {
          that.setData({
            imgUrl:"../../static/images/like2.png",
            isLike: true
          })
        }else{
          that.setData({
            imgUrl:"../../static/images/like1.png",
            isLike: true
          })
        }
        that.setData({
          status:res.data.data.result.status
        })
      }
    })
  },

  /**
   * 获取收藏列表
   */
  getcollectList(){
    let that = this
    console.log('------------that1',that);
    wx.request({
      url: 'https://www.xiaxueruo.com/api/collect/searchcollect?article_id='+this.options.id+'&user_id='+ wx.getStorageSync('user_id'),
      header: { 'content-type': 'application/json' },
      method: 'GET',//get或者post
      success: function (res) {
        console.log("..........status",res.data.data)//接口返回值
        if (res.data.data.result.status = 1) {
          that.setData({
            collectUrl:"../../static/images/collection2.png",
            isCollect: true
          })
        }else{
          that.setData({
            collectUrl:"../../static/images/collection1.png",
            isCollect: false
          })
        }
        that.setData({
          status:res.data.data.result.status
        })
      }
    })
  },

  onShareAppMessage() {
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: '文章'
        })
      }, 2000)
    })
    return {
      title: '文章',
      path: '/pages/index/index.wxml',
      promise 
    }
  }

})